package com.woniuxy.redis.service.impl;

import com.woniuxy.redis.entity.Student;
import com.woniuxy.redis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: linKe
 * @Date: 2022/1/5 16:57
 * @FileName: StudentServiceImpl
 * @version: 1.0
 * @Description: 学生服务层的具体实现类
 * 测试自定义redis 缓存操作的实现
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * key    student:1        student:2
     * @param id 学生id
     * @return 结果
     */
    @Override
    public Student getStudentById(int id) {
        Student student=null;
        // 获取string 操作对象
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        // 查询数据，先判断缓存中是否存在
        // 缓存没有，数据库查询，存入缓存,，缓存中有，缓存读取
        if(!redisTemplate.hasKey("student:"+id)){
            System.out.println("数据库查询，存入缓存");
            if(id==1){
                student=new Student(1, "zs");
            }else {
                student=new Student(2,"ls");
            }
            opsForValue.set("student:"+id,student);
        }else{
            System.out.println("缓存查询");
            student= (Student) opsForValue.get("student:"+id);
        }
        return  student;
    }

    /**
     * 多条件组合
     * key  studentsPage:1:10    studentsPage:2:10
     * @param pageIndex 当前页
     * @param pageSize  每页显示条数
     * @return 结果
     */
    @Override
    public List<Student> getStudentsByPage(int pageIndex, int pageSize) {
        List<Student> allStudents=new ArrayList<>();
        // 获取string 操作对象
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        for(int i=1;i<=100;i++){
            allStudents.add(new Student(i, "name"+i));
        }
        List<Student> students=new ArrayList<>();

        if(!redisTemplate.hasKey("studentspage:"+pageIndex+":"+pageSize)){
            System.out.println("查询数据库，存入缓存");
            for(int i=(pageIndex-1)*pageSize;i<pageIndex*pageSize;i++){
                students.add(allStudents.get(i));
            }
            opsForValue.set("studentspage:"+pageIndex+":"+pageSize,students);
        }else{
            System.out.println("缓存查询");
            students= (List<Student>) opsForValue.get("studentspage:"+pageIndex+":"+pageSize);
        }
        return students;
    }
}
